<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.taskName"
        placeholder="任务名称"
        style="width: 200px"
        clearable
        class="filter-item"
      ></el-input>
      <el-select v-model="listQuery.companyId" placeholder="所属单位" clearable class="filter-item">
        <el-option
          v-for="item in enterpriseList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <el-select
        v-model="listQuery.dangerLevel"
        placeholder="隐患级别"
        clearable
        style="width:130px"
        class="filter-item"
      >
        <el-option
          v-for="item in troubleGrades"
          :key="item.id"
          :label="item.dictValue"
          :value="item.id"
        />
      </el-select>
      <el-select
        v-model="listQuery.dangerRecitfyType"
        placeholder="整改类型"
        clearable
        class="filter-item"
        style="width: 130px"
      >
        <el-option
          v-for="item in troubleRectifyTypes"
          :key="item.id"
          :label="item.dictValue"
          :value="item.id"
        />
      </el-select>
      <!-- <el-date-picker
        v-model="listQuery.recitfyOverdate"
        type="date"
        value-format="yyyy/MM/dd"
        placeholder="发现时间"
        class="filter-item"
      ></el-date-picker>-->
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>

      <!-- <router-link :to="'troubleAdd'">
        <el-button class="filter-item" type="primary" icon="el-icon-edit">新增隐患</el-button>
      </router-link>-->
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column align="center" label="编号" min-width="60" prop="id"></el-table-column>
      <!-- <el-table-column type="index" label="序号" width="60" align="center"></el-table-column> -->
      <el-table-column min-width="200px" align="center" label="隐患名称" prop="dangerName"></el-table-column>
      <el-table-column min-width="200px" align="center" label="所属任务" prop="taskName"></el-table-column>
      <el-table-column min-width="200px" align="center" label="所属单位" prop="companyName"></el-table-column>

      <el-table-column min-width="100px" align="center" label="隐患级别" prop="dangerLevel">
        <template slot-scope="{row}">{{row.dangerLevel | levelFilter}}</template>
      </el-table-column>

      <el-table-column min-width="100px" align="center" label="整改类型">
        <template slot-scope="{row}">{{row.dangerRecitfyType|typeFilter}}</template>
      </el-table-column>
      <!-- <el-table-column min-width="100px" align="center" label="任务状态">
        <template slot-scope="{row}">{{row.taskState}}</template>
      </el-table-column>-->
      <el-table-column min-width="100px" align="center" label="隐患状态">
        <template slot-scope="{row}">{{row.dangerState|stateFilter}}</template>
      </el-table-column>

      <el-table-column class-name="status-col" label="发现人" width="100px" prop="discoverPerson"></el-table-column>
      <el-table-column class-name="status-col" label="发现时间" width="100px" prop="discoverDate"></el-table-column>
      <el-table-column class-name="status-col" label="发布时间" width="100px" prop="createTime"></el-table-column>
      <el-table-column class-name="status-col" label="整改限期" width="100px" prop="recitfyOverdate"></el-table-column>

      <el-table-column align="center" label="操作" width="100px" fixed="right">
        <template slot-scope="scope">
          <router-link :to="'troubleDetail/'+scope.row.id">
            <el-button size="small" icon="el-icon-view">查看</el-button>
          </router-link>
          <router-link
            :to="'troubleEdit/'+scope.row.id"
            v-if="scope.row.dangerState==1&&scope.row.taskState!=99"
          >
            <el-button size="small" icon="el-icon-edit" type="primary">编辑</el-button>
          </router-link>
          <router-link
            :to="'troubleCheck/'+scope.row.id"
            v-if="scope.row.dangerState==4||scope.row.dangerState==5"
          >
            <el-button type="success" size="small" icon="el-icon-edit">复查</el-button>
          </router-link>
          <!-- <router-link :to="'/message/messageDetail/83/check'">
            <el-button type="primary" size="small" icon="el-icon-edit">消息</el-button>
          </router-link>-->
          <el-button
            type="warning"
            size="small"
            @click="report(scope.row.id)"
            icon="el-icon-position"
          >上报</el-button>
          <el-button
            v-if="scope.row.dangerState==1"
            type="danger"
            size="small"
            @click="deleteTroubleById(scope.row.id)"
            icon="el-icon-close"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageIndex"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <el-dialog title="消息上报" :visible.sync="dialogMessageFormVisible">
      <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">
        <div class="createPost-main-container">
          <el-row>
            <el-col :span="24">
              <div class="postInfo-container">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label-width="130px" prop="msgTitle" label="消息标题:">
                      <el-input type="text" placeholder="请输入标题" v-model="postForm.msgTitle"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label-width="130px" label="发布对象:" prop="selectedText">
                      <el-input
                        type="text"
                        placeholder="选择对象"
                        v-model="postForm.selectedText"
                        disabled
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="2">
                    <el-form-item style="margin-left:5px">
                      <el-button
                        type="primary"
                        icon="el-icon-plus"
                        @click="personSelectDialogVisible=true"
                      ></el-button>
                    </el-form-item>
                  </el-col>
                  <el-col :span="10">
                    <el-form-item label-width="90px" label="级别:" prop="msgLevel">
                      <el-select v-model="postForm.msgLevel" placeholder="请选择等级">
                        <el-option label="一般" value="1"></el-option>
                        <el-option label="重要" value="2"></el-option>
                        <el-option label="紧急" value="3"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label-width="130px" label="消息内容:" prop="msgContent">
                      <el-input
                        type="textarea"
                        maxlength="1000"
                        show-word-limit
                        :rows="5"
                        placeholder="请输入消息内容"
                        v-model="postForm.msgContent"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item style="text-align: center;">
                      <el-button type="primary" @click="submitForm">发布</el-button>
                      <el-button @click="closeCurrentTag">关闭</el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </el-dialog>
    <el-dialog title="用户对象" :visible.sync="personSelectDialogVisible" class="selectPerson">
      <div class="left">
        <fieldset class="fieldInfo">
          <legend>
            <span>组织机构树</span>
          </legend>
          <div class="tree">
            <el-tree
              ref="organizationTree"
              :data="organizationData"
              node-key="id"
              default-expand-all
              :expand-on-click-node="false"
              @node-click="handleNodeClick"
              :props="defaultProps"
            ></el-tree>
          </div>
        </fieldset>
      </div>
      <div class="right">
        <fieldset class="fieldInfo">
          <legend>
            <span>所有人员</span>
          </legend>
          <div>
            <el-checkbox
              :indeterminate="isIndeterminate"
              v-model="checkAll"
              @change="handleCheckAllChange"
            >全选</el-checkbox>
            <div style="margin: 15px 0;"></div>
            <el-checkbox-group v-model="checkedUserList" @change="handleCheckedCitiesChange">
              <el-checkbox
                v-for="(user,index) in userListOptions"
                :key="index"
                :label="user.id"
              >{{user.userName}}</el-checkbox>
            </el-checkbox-group>
          </div>
        </fieldset>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="personSelectDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmUsers">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//状态 1:保存, 2:已通知(企业可查),3:整改中,4:待复查,5:复查不通过,6:已消除,-1:作废
import { fetchList, deleteTrouble, isReportDanger } from '@/api/troubles'
import { getBaseDicInfo } from '@/api/baseApi'
import { fetchEnterpriseListByUser } from '@/api/enterprise'
import { addMessage } from '@/api/message'
import { searchUser } from '@/api/user'
import { fetchTreeData, fetchUserListByOrg } from '@/api/organization'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
let that
export default {
  name: 'DangerTrouble',
  components: { Pagination },
  data() {
    const addMessage = {
      msgLevel: '', //等级
      msgContent: '', //消息内容
      msgTitle: '', //消息标题
      dipatcherIdList: [], //发布对象
      dispatchDate: '', //发布时间
      selectedText: '',
      workId: '',
      workType: 3
    }
    return {
      defaultProps: {
        label: 'name'
      },
      organizationData: [],
      isIndeterminate: true,
      checkAll: false,
      checkedUserList: [],
      dialogMessageFormVisible: false,
      personSelectDialogVisible: false, //用户选择对话框
      postForm: Object.assign({}, addMessage),
      userListOptions: [],
      rules: {
        msgLevel: [
          { required: true, message: '消息级别不能为空', trigger: 'blur' }
        ],
        selectedText: [
          { required: true, message: '用户对象不能为空', trigger: 'blur' }
        ],
        msgTitle: [
          { required: true, message: '消息标题不能为空', trigger: 'blur' }
        ],
        msgContent: [
          { required: true, message: '消息内容不能为空', trigger: 'blur' }
        ],
        dispatchDate: [
          { required: true, message: '发布时间不能为空', trigger: 'blur' }
        ]
      },

      enterpriseList: [],
      list: null,
      total: 0,
      listLoading: true,
      troubleGrades: [], //隐患级别
      troubleRectifyTypes: [], //整改类型
      listQuery: {
        taskName: '',
        pageIndex: 1,
        limit: 10,
        companyId: '',
        discoverPerson: '',
        discoverDate: '',
        dangerAppendixCrudeFileIds: [], //修改前的附件对象id数组
        dangerAppendixUpdateFileIds: [], //修改后的附件对象id数组
        dangerContent: '', //隐患描述
        dangerName: '', //隐患名称
        dangerLevel: '', //隐患级别
        dangerRecitfyType: null, //隐患整改类型
        dangerState: null, //状态
        id: '',
        pType: 2, //查询人员类型
        recitfyOverdate: '', //整改期限格式2020/04/30
        recitfyRequirement: '' //整改要求
      }
    }
  },
  beforeCreate: function() {
    that = this
  },
  created() {
    this.getTreeData()
    const taskId = this.$route.query && this.$route.query.taskId
    const level = this.$route.query && this.$route.query.level

    console.log('level-----------', level, typeof level)
    // console.log('taskId1111111111111', this.$route.query)
    // console.log('taskId1111111111111', this.$route.query.taskId)
    // console.log('taskId1111111111111', taskId)
    if (Number(taskId)) {
      this.listQuery.taskId = taskId
      this.listQuery.dangerState = 1
      this.getList()
    } else {
      if (!level) {
        this.getList()
      } else {
        this.listQuery.dangerLevel = Number(level)
        this.getList()
      }
    }
    this.getEnterpriseList()
    this.getTroubleGradesList()
    this.getRectifyTypeList()
  },
  filters: {
    stateFilter(state) {
      const stateMap = {
        1: '草稿',
        2: '待整改',
        3: '整改中',
        4: '待复查',
        5: '复查不通过',
        6: '已消除'
      }
      return stateMap[state]
    },
    typeFilter(typeId) {
      let result = ''
      that.troubleRectifyTypes.map((type) => {
        if (type.id == typeId) {
          result = type.dictValue
        }
      })
      return result
    },

    levelFilter(levelId) {
      let result = ''
      that.troubleGrades.map((level) => {
        if (level.id == levelId) {
          result = level.dictValue
        }
      })
      return result
    }
  },
  methods: {
    report(dangerId) {
      isReportDanger({ dangerId }).then((res) => {
        if (res.code == 20000) {
          if (res.data.id == 0) {
            //未上报
            this.dialogMessageFormVisible = true
            this.postForm.workId = dangerId
            this.postForm.workType = 3
          } else {
            this.$router.push(`/message/messageDetail/${res.data.id}/check`)
          }
        }
      })
    },
    getTroubleGradesList() {
      getBaseDicInfo({ typeId: 2 }).then((response) => {
        this.troubleGrades = response.data
      })
    },
    getRectifyTypeList() {
      getBaseDicInfo({ typeId: 1 }).then((response) => {
        this.troubleRectifyTypes = response.data
      })
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then((response) => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
        // this.listQuery = { pageIndex: 1, limit: 10, pType: 2 }
      })
    },
    getEnterpriseList() {
      fetchEnterpriseListByUser().then((response) => {
        // console.log(response.data)
        this.enterpriseList = response.data
      })
    },
    handleFilter() {
      this.getList()
    },
    deleteTroubleById(dangerId) {
      //删除隐患
      this.$confirm('此操作将永久该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteTrouble({ dangerId }).then((res) => {
            if (res.success) {
              this.$notify({
                title: '成功',
                message: '删除隐患成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            } else {
              this.$notify({
                title: '失败',
                message: '删除隐患失败',
                type: 'error',
                duration: 2000
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 获取用户对象
    getRemoteUserList(orgId) {
      // this.personSelectDialogVisible = true
      fetchUserListByOrg(orgId).then((response) => {
        // if (!response.data.records) return
        this.userListOptions = response.data.map((v) => {
          return {
            id: v.id,
            userLoginAccount: v.userLoginAccount,
            userName: v.userName
          }
        })
        // console.log(this.userListOptions)
      })
    },
    handleNodeClick(data, node) {
      console.log(data, node)
      this.getRemoteUserList(data.id)
    },
    getTreeData() {
      fetchTreeData({
        rootId: 0
      }).then((response) => {
        console.log(response.data)
        this.organizationData = response.data
      })
    },
    handleCheckAllChange(val) {
      this.checkedUserList = val
        ? this.userListOptions.map((u) => {
            return u.id
          })
        : []
      this.isIndeterminate = false
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length
      this.checkAll = checkedCount === this.userListOptions.length
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.userListOptions.length
    },
    closeCurrentTag() {
      this.dialogMessageFormVisible = false
    },
    confirmUsers() {
      this.postForm.dipatcherIdList = this.checkedUserList
      this.postForm.selectedText = `已选择${this.checkedUserList.length}人`
      this.personSelectDialogVisible = false
    },
    // fetchData(id) {
    //   fetchMessage(id)
    //     .then((response) => {
    //       this.postForm = response.data

    //       // just for test
    //       //this.postForm.title += `   Article Id:${this.postForm.id}`
    //       this.postForm.content_short += `   Article Id:${this.postForm.id}`

    //       // set tagsview title
    //       this.setTagsViewTitle()

    //       // set page title
    //       this.setPageTitle()
    //     })
    //     .catch((err) => {
    //       console.log(err)
    //     })
    // },
    // setTagsViewTitle() {
    //   const title = '编辑'
    //   const route = Object.assign({}, this.tempRoute, {
    //     title: `${title}-${this.postForm.id}`
    //   })
    //   this.$store.dispatch('tagsView/updateVisitedView', route)
    // },
    // setPageTitle() {
    //   const title = '编辑'
    //   document.title = `${title} - ${this.postForm.id}`
    // },
    submitForm() {
      console.log(this.postForm)
      this.$refs.postForm.validate((valid) => {
        if (valid) {
          addMessage(this.postForm).then((res) => {
            if (res.success) {
              this.getList()
              this.$notify({
                title: '成功',
                message: '消息发布成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: '失败',
                message: '消息发布失败',
                type: 'error',
                duration: 2000
              })
            }
          })
        } else {
          this.$notify({
            title: '失败',
            message: '消息发布验证失败',
            type: 'error',
            duration: 2000
          })
        }
      })
    }
  }
}
</script>

<style scoped  lang="scss" >
.app-container /deep/ .pagination-container {
  margin-top: 0;
  padding: 16px 16px;
}
.app-container /deep/ .el-button + .el-button {
  margin-left: 0;
}
@import '~@/styles/mixin.scss';
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.searchBar {
  margin-bottom: 10px;
}
.selectPerson /deep/ .el-dialog__body {
  display: flex;
  .left {
    flex: 1;
  }
  .right {
    flex: 1;
  }
}
</style>

